#include <REGX52.H>


sbit I2C_SCL = P2^1;
sbit I2C_SDA = P2^0;

// 根据时序图编写代码


void I2C_Start()
{
	I2C_SCL = 1;
	I2C_SDA = 1;
	I2C_SDA = 0;
	// SCL拉低，是为了拼接时序图
	I2C_SCL = 0;
}

void I2C_Stop()
{
	I2C_SDA = 0;
	I2C_SCL = 1;
	
	I2C_SDA = 1;
}

void I2C_SendByte(unsigned char Data)
{
	// 发送之前，SCL就是处于一个低电平
	// 因此发送逻辑应该是，SDA放入数据，拉高SCL，再拉低SCL
	unsigned char i;
	for(i = 0; i < 8; i++)
	{

		I2C_SDA = Data & (0x80 >> i);
		I2C_SCL = 1;
		I2C_SCL = 0;
	}
}

unsigned char I2C_RecvByte()
{
	// 我们是主机，主机是在SCL高电平期间，读取SDA
	// 从机发送数据则和主机发送数据的规则一致
	unsigned char Data = 0x00;
	unsigned char i;
	// 主机释放SDA 
	I2C_SDA = 1;
	
	for(i = 0; i < 8; i++)
	{
		I2C_SCL = 1;
		if(I2C_SDA) 
			Data |= (0x80 >> i);
		I2C_SCL = 0;
			
	}

	return Data;
}


void I2C_SendAck(unsigned char Ack)
{
	I2C_SDA = Ack;
	I2C_SCL = 1;
	I2C_SCL = 0;
}


unsigned char I2C_RecvAck()
{
	unsigned char Ack;
	I2C_SDA = 1;
	
	I2C_SCL = 1;
	Ack = I2C_SDA;
	I2C_SCL = 0;
	
	return Ack;
}

